﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ITSTOREBLL;
using ITStore.Models;
using System.Web.Security;

namespace ITStore.Controllers
{ 
    public class TaiKhoanController : Controller
    {
        private ITStoreEntities db = new ITStoreEntities();

        //
        // GET: /TaiKhoan/Details/5

        public ViewResult Details(int id)
        {
            TaiKhoan taikhoan = db.TaiKhoans.Single(t => t.tk_ID == id);
            return View(taikhoan);
        }

        //
        // GET: /TaiKhoan/Create

        public ActionResult index()
        {
            ViewBag.tk_GioiTinh = new SelectList(db.GioiTinhs, "gt_ID", "gt_Loai");
            ViewBag.tk_Loai = new SelectList(db.LoaiTaiKhoans, "ltk_ID", "ltk_Ten");
            ViewBag.tk_TinhThanh = new SelectList(db.TinhThanhs, "tt_ID", "tt_Ten");
            return View();
        } 

        //
        // POST: /TaiKhoan/Create

        [HttpPost]
        public ActionResult index(TaiKhoan taikhoan)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus;
                Membership.CreateUser(taikhoan.tk_TenDangNhap, taikhoan.tk_MatKhau, taikhoan.tk_Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(taikhoan.tk_TenDangNhap, false /* createPersistentCookie */);
                    Roles.AddUserToRole(taikhoan.tk_TenDangNhap, Request.Form["tk_Loai"]);
                    db.TaiKhoans.AddObject(taikhoan);
                    db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            ViewBag.tk_GioiTinh = new SelectList(db.GioiTinhs, "gt_ID", "gt_Loai", taikhoan.tk_GioiTinh);
            ViewBag.tk_Loai = new SelectList(db.LoaiTaiKhoans, "ltk_ID", "ltk_Ten", taikhoan.tk_Loai);
            ViewBag.tk_TinhThanh = new SelectList(db.TinhThanhs, "tt_ID", "tt_Ten", taikhoan.tk_TinhThanh);
            return View(taikhoan);
        }
        
        //
        // GET: /TaiKhoan/Edit/5
 
        public ActionResult Edit(int id)
        {
            TaiKhoan taikhoan = db.TaiKhoans.Single(t => t.tk_ID == id);
            ViewBag.tk_GioiTinh = new SelectList(db.GioiTinhs, "gt_ID", "gt_Loai", taikhoan.tk_GioiTinh);
            ViewBag.tk_Loai = new SelectList(db.LoaiTaiKhoans, "ltk_ID", "ltk_Ten", taikhoan.tk_Loai);
            ViewBag.tk_TinhThanh = new SelectList(db.TinhThanhs, "tt_ID", "tt_Ten", taikhoan.tk_TinhThanh);
            return View(taikhoan);
        }

        //
        // POST: /TaiKhoan/Edit/5

        [HttpPost]
        public ActionResult Edit(TaiKhoan taikhoan)
        {
            if (ModelState.IsValid)
            {
                db.TaiKhoans.Attach(taikhoan);
                db.ObjectStateManager.ChangeObjectState(taikhoan, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
                //return RedirectToAction("Index");
            }
            ViewBag.tk_GioiTinh = new SelectList(db.GioiTinhs, "gt_ID", "gt_Loai", taikhoan.tk_GioiTinh);
            ViewBag.tk_Loai = new SelectList(db.LoaiTaiKhoans, "ltk_ID", "ltk_Ten", taikhoan.tk_Loai);
            ViewBag.tk_TinhThanh = new SelectList(db.TinhThanhs, "tt_ID", "tt_Ten", taikhoan.tk_TinhThanh);
            return View(taikhoan);
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult DangNhap()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DangNhap(TTDangNhap _ttdangnhap, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(_ttdangnhap.UserName, _ttdangnhap.pass))
                {
                    FormsAuthentication.SetAuthCookie(_ttdangnhap.UserName, _ttdangnhap.remember);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "sai tên đăng nhập hoặc mật khẩu!");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(_ttdangnhap);
        }

        public ActionResult DangXuat()
        {
            FormsAuthentication.SignOut();
            DonHangBLL dhbll = new DonHangBLL();
            dhbll.XoaTatCaDonHang(this.HttpContext);
            this.HttpContext.Session.Clear();
            return RedirectToAction("Index", "Home");
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}